package com.xjgz.aio.socket.buffer;

import java.nio.ByteBuffer;
import java.util.concurrent.Semaphore;

public final class VirtualBuffer {

    private final BufferPage bufferPage;

    private final Semaphore clean = new Semaphore(1);

    private final ByteBuffer buffer;

    VirtualBuffer(BufferPage bufferPage, ByteBuffer buffer) {
        this.bufferPage = bufferPage;
        this.buffer = buffer;
    }

    public static VirtualBuffer wrap(ByteBuffer buffer) {
        return new VirtualBuffer(null, buffer);
    }

    public ByteBuffer buffer() {
        return buffer;
    }

    void reset() {
        this.buffer.clear();
        clean.release();
    }

    public void clean() {
        if (clean.tryAcquire()) {
            if (bufferPage != null) {
                bufferPage.clean(this);
            }
        } else {
            throw new UnsupportedOperationException("buffer has cleaned");
        }
    }

    @Override
    public String toString() {
        return buffer.toString();
    }
}
